#pragma once
#include <iostream>
#include <string>
#include <vector>
#include "INETADDR.hpp"
#include "Log.hpp"
using namespace std;
class Route
{
    private:
    bool IsExist(INETADDR& addr)
    {
        for(auto& e:_onlines_users)
        {
            if(addr == e)
            {
                return true;
            }
        }
        return false;
    }
    void AddUser(INETADDR& addr)
    {
        LOG(LogLevel::INFORMATION)  << "新增一个在线用户# " << addr.StringAddr();
        _onlines_users.push_back(addr);
    }
    void DeleteUser(INETADDR& addr)
    {
        LOG(LogLevel::INFORMATION) << "删除一个在线用户# " << addr.StringAddr();

        for(auto iter = _onlines_users.begin();iter != _onlines_users.end();iter++)
        {
            if(addr == *iter)
            {
                _onlines_users.erase(iter);
                break;
            }
        }
        
    }
public:
    Route()
    {
    }
    void RouteMSaaage(int sockfd,const string& message,INETADDR& addr)
    {
        if(!IsExist(addr))
        {
            AddUser(addr);
        }
        string s = addr.StringAddr() + + "# " + message;
        for(auto& e:_onlines_users)
        {
            sendto(sockfd,s.c_str(),sizeof(s),0,(const struct sockaddr*)&(e.NetAddr()),sizeof(e.NetAddr()));
        }
        if(message == "quit")
        {
            DeleteUser(addr);
        }


    }

    ~Route()
    {
    }

private:
    vector<INETADDR> _onlines_users;
};